import logging
from flask import render_template, g, redirect, request, jsonify, abort
from info import constants, db
from info.models import Category, News, User
from info.until.common import outside
from info.until.qiniu_third import storage
from info.until.response_code import RET
from . import personal_blu


@personal_blu.route('/user_center')
@outside
def user_center():
    use_data = g.use
    if not use_data:
        return redirect("/")
    data = {
        "use": use_data.to_dict() if use_data else None
    }
    return render_template("user.html", data=data)


@personal_blu.route('/base_info', methods=["get", "post"])
@outside
def info():
    use = g.use
    if request.method == "GET":
        data = {
            "use": use.to_dict()
        }
        return render_template("user_base_info.html", data=data)
    else:
        nick_name = request.json.get("nick_name")
        signature = request.json.get("signature")
        gender = request.json.get("gender")

        if not all([nick_name, signature, gender]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        if gender not in ["MAN", "WOMAN"]:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

        # 把修改的数据保存到数据库
        use.nick_name = nick_name
        use.signature = signature
        use.gender = gender

        return jsonify(errno=RET.OK, errmsg="OK")


@personal_blu.route('/pic_info', methods=["get", "post"])
@outside
def pic_info():
    use = g.use

    if request.method == "GET":
        data = {
            "use": use.to_dict()
        }
        return render_template("user_pic_info.html", data=data)

    else:
        # 读取用户传来的二进制头像
        try:
            result = request.files.get("avatar").read()
        except Exception as e:
            logging.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        if not result:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        # 将用户传的头像上传到七牛云,并且获取七牛云的图片路径
        try:
            ret_key = storage(result)
        except Exception as e:
            logging.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传头像失败")
        # 保存头像路径到数据库
        try:
            use.avatar_url = "/" + ret_key
        except Exception as e:
            logging.error(e)
            return jsonify(errno=RET.DATAERR, errmsg="保存头像失败")

        data = {
            "avatar_url": constants.QINIU_DOMIN_PREFIX + "/" + ret_key
        }

        return jsonify(errno=RET.OK, errmsg="OK", data=data)


@personal_blu.route('/pass_info', methods=["get", "post"])
@outside
def pass_info():
    use = g.use
    if request.method == "GET":
        return render_template("user_pass_info.html")
    else:
        old_password = request.json.get("old_password")
        new_password = request.json.get("new_password")

        if not all([old_password, new_password]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

        if not use.check_password(old_password):
            return jsonify(errno=RET.PWDERR, errmsg="原密码错误")

        use.password = new_password

        return jsonify(errno=RET.OK, errmsg="Ok")


@personal_blu.route('/collection')
@outside
def collection():
    """
    显示收藏信息
    :return:
    """
    use = g.use
    page = request.args.get("page", 1)
    try:
        page = int(page)
    except Exception as e:
        logging.error(e)
        page = 1
    total_page = None
    items_li = None
    try:
        paginate = use.collection_news.paginate(page, constants.HOME_PAGE_MAX_NEWS, False)
        page = paginate.page
        total_page = paginate.pages
        items_li = paginate.items
    except Exception as e:
        logging.error(e)

    items = []
    for news in items_li:
        items.append(news.to_basic_dict())

    data = {
        "page": page,
        "total_page": total_page,
        "collections": items
    }
    return render_template("user_collection.html", data=data)


@personal_blu.route('/news_release', methods=["get", "post"])
@outside
def news_release():
    use = g.use
    if request.method == "GET":
        category = []
        try:
            category = Category.query.all()
        except Exception as e:
            logging.error(e)

        categories = []
        for category_model in category:
            categories.append(category_model.to_dict())

        categories.pop(0)

        data = {
            "categories": categories
        }
        return render_template("user_news_release.html", data=data)
    else:
        title = request.form.get("title")
        category_id = request.form.get("category_id")
        digest = request.form.get("digest")
        index_image = request.files.get("index_image")
        content = request.form.get("content")
        source = use.nick_name

        if not all([title, category_id, digest, index_image, content, source]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        try:
            category_id = int(category_id)
        except Exception as e:
            logging.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        try:
            # 读取图片的二进制
            index_image = index_image.read()
        except Exception as e:
            logging.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

        # 上传图片到七牛云
        try:
            ret_key = storage(index_image)
        except Exception as e:
            logging.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")

        news = News()
        news.category_id = category_id
        news.source = source
        news.content = content
        news.digest = digest
        news.title = title
        news.status = 1
        news.user_id = use.id
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + "/" + ret_key

        try:
            db.session.add(news)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            logging.error(e)
            return jsonify(errno=RET.DATAERR, errmsg="数据保存失败")

        data = {
            "news": news.to_basic_dict()
        }
        return jsonify(errno=RET.OK, errmsg="OK", data=data)


@personal_blu.route('/news_list')
@outside
def news_list():
    page = request.args.get("page", 1)
    try:
        page = int(page)
    except Exception as e:
        logging.error(e)

    # 查询当前用户的发布新闻
    use = g.use
    news_list = []
    current_page = 1
    total_page = 1
    try:
        # paginate= News.query.filter(News.user_id==use.id).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        paginate = News.query.filter(News.user_id == use.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        logging.error(e)

    page_items = []
    for item in news_list:
        page_items.append(item.to_review_dict())

    data = {
        "page": current_page,
        "total_page": total_page,
        "page_items": page_items
    }

    return render_template("user_news_list.html", data=data)


@personal_blu.route('/follow')
@outside
def follow():
    """
    个人中心的关注(登入者关注的人)
    :return:
    """
    page = request.args.get("page", 1)
    try:
        page = int(page)
    except Exception as e:
        logging.error(e)
    use = g.use
    total_page = 1
    user_items = []
    try:
        paginate = use.followed.paginate(page, constants.USER_FOLLOWED_MAX_COUNT)
        page = paginate.page
        total_page = paginate.pages
        user_items = paginate.items
    except Exception as e:
        logging.error(e)

    user_items_li = []
    for user in user_items:
        user_items_li.append(user.to_dict())

    data = {
        "page": page,
        "total_page": total_page,
        "user_items_li": user_items_li
    }
    return render_template("user_follow.html", data=data)


@personal_blu.route('/other')
@outside
def other():
    """
    判断登入时是否关注
    :return:
    """
    use = g.use
    other_id = request.args.get("other_id")

    if not other_id:
        abort(404)
    try:
        others = User.query.get(other_id)
    except Exception as e:
        logging.error(e)
        return render_template("other.html", errmsg="数据库查询错误")
    if not others:
        return render_template("other.html", errmsg="该用户未查询到")

    is_followed = False
    # 如果用户登入，则判断是否登入
    if use and others:
        if use in others.followers:
            is_followed = True

    data = {
        "use": use.to_dict() if use else None,
        "others": others.to_dict() if others else None,
        "is_followed": is_followed
    }
    return render_template("other.html", data=data)


@personal_blu.route('/other_news')
@outside
def other_news():
    other_id = request.args.get("other_id")
    page = request.args.get("page", 1)

    if not all([other_id, page]):
        abort(404)
    try:
        page = int(page)
    except Exception as e:
        logging.error(e)
    try:
        others = User.query.get(other_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据库查询错误")
    if not others:
        return jsonify(errno=RET.NODATA, errmsg="未查询到此用户")

    try:
        paginate = others.news_list.paginate(page, constants.USER_FOLLOWED_MAX_COUNT)
        page = paginate.page
        total_pages = paginate.pages
        other_news_li = paginate.items
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据库查询失败")
    other_news = []
    for items in other_news_li:
        other_news.append(items.to_dict())

    data = {
        "page": page,
        "total_page": total_pages,
        "other_news": other_news
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)
